using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SpoonCore2.Message;
using SpoonCore2.Client;

namespace SpoonCore2.Service.Lookup
{
	class LookupMessage : AbstractMessage
	{
		private static readonly Random _rand = new Random();
		private int _id = _rand.Next();

		private ClientInfo _sender;
		private SpoonIdentifier _typeId = SpoonIdentifier.Empty;
		private SpoonIdentifier _lookupId = new SpoonIdentifier();
		private RequestTypeValue _requestType = RequestTypeValue.Request;
		private StorageTypeValue _storageType = StorageTypeValue.Store;
		private byte[] _data;
		private int _degree;

		public enum RequestTypeValue : byte { Request, Response }
		public enum StorageTypeValue : byte
		{
			Store, Load, Check
		}

		public RequestTypeValue RequestType
		{
			get { return _requestType; }
			set { _requestType = value; }
		}

		public StorageTypeValue StorageType
		{
			get { return _storageType; }
			set { _storageType = value; }
		}

		public int Id
		{
			get { return _id; }
			set { _id = value; }
		}

		public SpoonIdentifier TypeId
		{
			get { return _typeId; }
			set { _typeId = value; }
		}

		public SpoonIdentifier LookupId
		{
			get { return _lookupId; }
			set { _lookupId = value; }
		}

		public byte[] Data
		{
			get { return _data; }
			set { _data = value; }
		}

		public ClientInfo Sender
		{
			get { return _sender; }
			set { _sender = value; }
		}

		public int Degree
		{
			get { return _degree; }
			set { _degree = value; }
		}

		public override void GetBytes(BinaryWriter bw)
		{
			bw.Write(Id);
			bw.Write(_sender != null);
			if (_sender != null) _sender.GetBytes(bw);
			bw.Write(LookupId.GetBytes());
			bw.Write((byte)RequestType);
			bw.Write((byte)StorageType);
			bw.Write(Degree);
			bw.Write(Data != null);
			if (Data != null)
			{
				bw.Write(Data.Length);
				bw.Write(Data);
			}
		}

		public override void SetBytes(IService service, BinaryReader br)
		{
			Id = br.ReadInt32();
			if (br.ReadBoolean()) _sender = new ClientInfo(service, br);
			LookupId = new SpoonIdentifier(br);
			RequestType = (RequestTypeValue)br.ReadByte();
			StorageType = (StorageTypeValue)br.ReadByte();
			Degree = br.ReadInt32();
			if (br.ReadBoolean())
			{
				int count = br.ReadInt32();
				Data = br.ReadBytes(count);
			}
		}
	}
}